<template>
	<view class="box">
		<view class="head">
			<view class="btnStyle add btn" @click="addFn">
				添加 </view>
			<el-pagination :current-page="1" :page-size="3" :page-sizes="sizes" small @size-change="getSize"
				@current-change="getPage" layout="total, sizes, prev, pager, next, jumper"
				:total="filterDatas.length " />
		</view>


		<el-table :data='tables' max-height="650">
			<el-table-column prop="id" width="120" label="账户ID" align="center"
				:formatter="idFormatter"></el-table-column>
			<el-table-column prop="account" width="120" label="账户" align="center"></el-table-column>
			<el-table-column label="头像" align="center" width="100">
				<template slot-scope="scope">
					<image :src="scope.row.avatar" mode="scaleToFill" class="avatar"></image>
				</template>
			</el-table-column>
			<el-table-column prop="name" class="text-overflow" width="100" label="用户名" align="center"></el-table-column>
			<el-table-column prop="email" width="150" label="邮箱" align="center"></el-table-column>
			<el-table-column prop="pwd" class="text-overflow" label="密码" align="center" width="100"></el-table-column>
			<el-table-column prop="height" width="60" label="身高" align="center"></el-table-column>
			<el-table-column prop="weigh" width="60" label="体重" align="center"></el-table-column>
			<el-table-column prop="birthdate" width="100" label="生日" align="center"></el-table-column>
			<el-table-column :formatter="statusFormatter" prop="status" sortable label="用户状态" width="100"
				align="center"></el-table-column>
			<el-table-column fixed="right" label="操作" align="center">
				<template #header>
					<el-input @input="filterFn" v-model="search" size="small" placeholder="请输入用户账号" />
				</template>
				<template slot-scope="scope">
					<view v-if="scope.row.status==0" class="btnStyle stop" style="margin-right: 15px;"
						@click="statusChange(scope.row.id,1  )">停用
					</view>
					<view v-else class="btnStyle start" style="margin-right: 15px;"
						@click="statusChange(scope.row.id,0 )">启用
					</view>
					<view class="btnStyle" style="margin-right: 15px;" @click="delDialogFn(scope.row.id  )">
						删除
					</view>
					<view class="btnStyle" @click="amend(scope.row )">修改
					</view>
				</template>
			</el-table-column>
		</el-table>
		<uni-popup ref="user" background-color="#fff">
			<view class="popup-content">
				<view class="popup_head">{{activeId?'修改':'新增'}}</view>
				<uni-forms ref="formRef" labelWidth="80px" :modelValue="formData" label-align="center" :rules="rules">
					<uni-forms-item label="用户名" required name="name">
						<uni-easyinput v-model.trim="formData.name" placeholder="请输入用户名" maxlength="20" />
					</uni-forms-item>
					<uni-forms-item label="手机号" required name="account">
						<uni-easyinput maxlength="11" v-model.trim="formData.account" placeholder="请输入手机号" />
					</uni-forms-item>
					<uni-forms-item label="邮箱号" required name="email">
						<uni-easyinput v-model.trim="formData.email" placeholder="请输入邮箱号" maxlength="20" />
					</uni-forms-item>
					<uni-forms-item label="密码" required name="pwd">
						<uni-easyinput v-model.trim="formData.pwd" placeholder="请输入密码" maxlength="20" />
					</uni-forms-item>
					<view v-if="activeId&&!isAdmend" class="videos">
						<view class="amendVideo" @click="isAdmend=true;formData.avatar=[]">修改头像</view>
						<image :src="formData.avatar[0]" mode="widthFix" style="width: 100px;"></image>
					</view>
					<uni-forms-item label="上传图片" required name="avatar" v-else>
						<uni-file-picker limit="1" style="padding: 0 10px;" v-model="formData.avatar"
							file-mediatype="image"></uni-file-picker>
					</uni-forms-item>
				</uni-forms>
				<view class=" inner-center">
					<button size="mini" class="btn" @click="submit">{{activeId==''?'提交':'修改'}}</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		emailVerify,
		phoneVerify,
		pwdVerify
	} from '../util/verify.js'
	import {
		verify,
		addData,
		getUserData,
		remove,
		check
	} from '../database/index.js'
	import {
		onBeforeMount,
		onMounted
	} from "vue";
	export default {
		name: 'user',
		data() {
			return {
				isAdmend: false,
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '名字不能为空'
						}]
					},
					pwd: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}, {
							validateFunction: async function(rule, value, data, callback) {
								let [res, msg] = await pwdVerify(value)
								if (!res) {
									callback(msg)
								}
								return true
							}
						}]
					},
					account: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							validateFunction: async function(rule, value, data, callback) {
								let [res, msg] = await phoneVerify(value)
								if (!res) {
									callback(msg)
								}
								return true
							}
						}]
					},
					email: {
						rules: [{
							required: true,
							errorMessage: '邮箱不能为空'
						}, {
							validateFunction: async function(rule, value, data, callback) {
								let [res, msg] = await emailVerify(value)
								if (!res) {
									callback(msg)
								}
								return true
							}
						}]
					},
					avatar: {
						rules: [{
							required: true,
							errorMessage: '图片不能为空'
						}]
					}
				},
				formData: {
					name: '',
					avatar: [],
					email: '',
					account: '',
					pwd: ''
				},
				activeId: '',
				curentIndex: '',
				search: '',
				datas: [],
				page: 1,
				size: 3,
				sizes: [3, 5, 10],
				filterDatas: [],
				tables: [],

			}
		},

		methods: {
			idFormatter(row) {
				return row.id.slice(0, 10)
			},
			statusFormatter(row) {
				return row.status == 0 ? '正常' : '停用'
			},
			async show() {
				this.datas = await getUserData()
				this.filterFn()
			},
			addFn() {
				getUserData()
				this.clear()
				this.activeId = ''
				this.$refs.user.open()
			},
			amend(data) {
				this.activeId = data.id
				this.formData.name = data.name
				this.formData.avatar = [data.avatar]
				this.formData.email = data.email
				this.formData.account = data.account
				this.formData.pwd = data.pwd
				this.$refs.user.open()
			},
			async statusChange(id, type) {
				let [admend, msg] = await verify('user', {
					_id: id
				}, {
					user_status: type == 0 ? 0 : 1
				})
				if (admend) {
					for (let data of this.datas) {
						if (data.id === id) {
							data.status = type == 0 ? 0 : 1
						}
					}
					this.filterFn()
					this.$showMsg('修改成功')
				} else {
					this.$showMsg('修改失败')
				}
			},
			async delDialogFn(id) {
				let self = this
				uni.showModal({
					title: '提示',
					content: '是否确定删除该用户？',
					success: async function(res) {
						if (res.confirm) {
							let isdel = await remove('user', {
								_id: id
							})
							await remove('courserCollect', {
								course_collector: id
							})
							await remove('dynamicLike', {
								liker: id
							})
							await remove('heightRecord', {
								user_Id: id
							})
							await remove('sportCollect', {
								sport_collector: id
							})
							await remove('sportTrain', {
								user_id: id
							})
							await remove('weighRecord', {
								user_Id: id
							})
							if (isdel) {
								self.datas = self.datas.filter(item => item.id !== id);
								self.filterFn()
								self.$showMsg('删除成功')
							} else {
								self.$showMsg('删除失败')
							}
						}
					}
				});
			},
			async clear() {
				this.formData = {
					name: '',
					avatar: [],
					email: '',
					account: '',
					pwd: ''
				}
				this.isAdmend = false
				this.show()
			},
			async upload() {
				let account = ''
				let email = ''
				for (let data of this.datas) {
					if (data.id == this.activeId) {
						account = data.account
						email = data.email
					}
				}
				let [isaccount, msgaccount] = await check('user', [
					`user_account == "${this.formData.account}" && user_account != "${account}"`
				])
				if (!isaccount) {
					this.$showMsg('该账户已存在')
					return
				}
				let [isemail, msgemail] = await check('user', [
					`user_email == "${this.formData.email}" && user_email != "${email}"`
				])
				if (!isemail) {
					this.$showMsg('该邮箱已存在')
					return
				}
				if (this.activeId) {
					this.$refs.user.close()
					let [admend, msg] = await verify('user', {
						_id: this.activeId
					}, {
						user_account: this.formData.account,
						user_name: this.formData.name,
						user_email: this.formData.email,
						user_avatar: this.formData.avatar[0].url ? this.formData.avatar[0].url : this.formData
							.avatar[0],
						user_pwd: this.formData.pwd
					})
					if (admend) {
						this.filterFn()
						this.updateData()
						this.$showMsg('修改成功')
						this.clear()
					} else {
						this.$showMsg('修改失败')
					}
				} else {
					this.$refs.user.close()
					let [isadd, id, msg] = await addData('user', {
						user_account: this.formData.account,
						user_name: this.formData.name,
						user_email: this.formData.email,
						user_avatar: this.formData.avatar[0].url,
						user_pwd: this.formData.pwd
					})

					if (isadd) {
						this.$showMsg('添加成功')
						this.datas.push({
							name: this.formData.name,
							avatar: this.formData.avatar[0].url,
							email: this.formData.email,
							account: this.formData.account,
							pwd: this.formData.pwd,
							id: id,
							height: 160,
							weigh: 60,
							birthdate: '',
							status: 0
						})
						this.clear()
						this.filterFn()
					} else {
						this.$showMsg('添加失败')
					}
				}

			},
			async submit() {
				let self = this
				this.$refs.formRef.validate().then(async res => {
					self.upload()
				}).catch(err => {
					console.log('err', err);
				})
			},

			getPage(val) {
				this.page = val
				this.filterFn(val, 2)
			},
			getSize(val) {
				this.size = val
				this.filterFn(val, 1)

			},
			updateData(url) {
				for (let data of this.datas) {
					if (data.id == this.activeId) {
						data.account = this.formData.account
						data.name = this.formData.name
						data.email = this.formData.email
						data.avatar = url
						data.pwd = this.formData.pwd
					}
				}
			},
			filterFn(val, type) {
				let size = this.size
				let page = this.page
				if (type == 1) {
					size = val
				} else if (type == 2) {
					page = val
				}
				let table = this.datas.filter(
					(data) =>
					!this.search ||
					data.account.toLowerCase().includes(this.search.toLowerCase())
				)
				console.log(table);
				let start = page == 1 ? 0 : (page - 1) * size
				let end = size * page > table.length ? table.length : size * page
				this.filterDatas = table.slice(0)
				if (start >= end) {
					start = 0
				}
				this.tables = table.slice(start, end)
			}

		}
	}
</script>

<style lang="scss" scoped>
	::v-deep {
		uni-button[type=primary] {
			background-color: #4682B4;
		}
	}

	.videos {
		text-align: center;
		margin: 0 10px;
		margin-bottom: 20px;

		.amendVideo {
			text-align: right;
			margin-bottom: 10px;
		}
	}

	.btn {
		width: 100px;
		text-align: center;
		color: white;
		background-color: #4682B4;
	}

	::v-deep {
		.uni-popup__wrapper {
			width: 400px;
			border-radius: 10px;
			padding: 15px;
		}
	}

	::v-deep {
		.tip {
			.uni-popup__wrapper {
				width: 50px;
				border-radius: 10px;
				margin-top: 80px;
				margin-left: 500px;
			}
		}

	}

	.box {
		padding: 20px;
		color: black;

		uni-forms-item {
			margin-bottom: 20px;

			.uni-forms-item__content {
				width: 200px;
			}
		}

		.popup-content {
			padding: 10px 20px;

			.popup_head {
				padding-left: 30px;
				font-size: 25px;
				text-align: center;
				color: #4169E1;
				letter-spacing: 15px;
				margin-bottom: 10px;
			}
		}
	}

	.btnStyle {
		letter-spacing: 2px;
		color: white;
		background-color: #4682B4;
		width: 50px;
		text-align: center;
		margin-top: 10px;
		border-radius: 5px;
		padding: 5px;
		display: inline-block;
	}

	.start {
		background-color: green;
		color: white;
	}

	.stop {
		background-color: red;
		color: white;
	}

	.head {
		margin-bottom: 10px;
		display: flex;
		justify-content: space-between;
	}

	.add {
		padding: 5px 20px;

	}
</style>